package org.jtb.flickrportlet;

import org.jtb.quickr.ContactsGetListCriteria;
import org.jtb.quickr.ContactsGetPublicListCriteria;
import org.jtb.quickr.ContactsResponse;
import org.jtb.quickr.ContactsService;
import org.jtb.quickr.PeopleService;
import org.jtb.quickr.PersonResponse;
import org.jtb.quickr.QuickrException;
import org.jtb.quickr.UserResponse;

public class ContactsHandler {
    private ContactsBean contactsBean;
    private AuthHandler authHandler;
    private PrefsBean prefsBean;
   
    public ContactsBean getContactsBean() {
        return contactsBean;
    }
    
    public void setContactsBean(ContactsBean contactsBean) throws QuickrException {
        this.contactsBean = contactsBean;
        
        if (prefsBean.getUserName() != null && prefsBean.getUserName().length() > 0) {
            if (!contactsBean.isLoaded()) {
                load(contactsBean);
            }
        }
    }
    
    public void load(ContactsBean contactsBean) throws QuickrException {
        ContactsService cs = new ContactsService();
        ContactsResponse res;
        if (authHandler.isAuthenticated()) {
            ContactsGetListCriteria criteria = new ContactsGetListCriteria();
            criteria.setFilter(ContactsGetListCriteria.Filter.BOTH);
            res = cs.getList(authHandler.getToken(), criteria);
        } else {
            String userId = findByUserName(prefsBean.getUserName());
            ContactsGetPublicListCriteria criteria = new ContactsGetPublicListCriteria();
            criteria.setUserId(userId);
            res = cs.getPublicList(criteria);
        }
        
        contactsBean.setContacts(res.getContacts());
    }
    
    private String findByUserName(String userName) throws QuickrException {
        PeopleService ps = new PeopleService();
        UserResponse ur = ps.findByUserName(userName);
        String userId = ur.getNsId();
        
        return userId;
    }
    
    public void setAuthHandler(AuthHandler authHandler) {
        this.authHandler = authHandler;
    }
    
    public void setPrefsBean(PrefsBean prefsBean) {
        this.prefsBean = prefsBean;
    }
}
